﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using DevExpress.Web.Mvc;
using System.Data;
using System.IO;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 绩效评估专栏
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class PerformanceController : Common.AdminBaseController
    {
        //
        // GET: /Admin/Performance/
        /// <summary>
        ///绩效评估专栏
        /// </summary>
        /// <returns>主页视图</returns>
        [AuthorityActionFilter("m_Performance", Order = 1)]
        [LogPageActionFilter("绩效评估专栏", Order = 2)]
        public ActionResult Index()
        {
            string strwhere = "";
            List<Model.PerformancePrj> PerformancePrjList = GetPerformancePrjListList(strwhere, 1);
            return View(PerformancePrjList);
        }

        public ActionResult PerformanceEdit(string No)
        {
            Model.PerformancePrj performancePrjModel = new Model.PerformancePrj();
            if (No == null || No == "")
            {
                ViewData["PerformancePrjEntryList"] = "";
                performancePrjModel.FYear = DateTime.Now.Year - 1;

            }
            else
            {
                BLL.PerformancePrj PerformancePrjBLL = new BLL.PerformancePrj();
                performancePrjModel = PerformancePrjBLL.GetModel(decimal.Parse(No));
                BLL.PerformancePrjEntry PerformancePrjEntryBLL = new BLL.PerformancePrjEntry();
                ViewData["PerformancePrjEntryList"] = PerformancePrjEntryBLL.GetModelList("FPerformancePrjID=" + No);
            }
            return View(performancePrjModel);
        }

        public ActionResult PerformancePrjEntryPartial()
        {

            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();
            string No = Request.Params["FPerformancePrjID"] == null ? string.Empty : Request.Params["FPerformancePrjID"];

            List<Model.PerformancePrjEntry> modelList = new List<Model.PerformancePrjEntry>();
            if (No == "0")//数据在未保存到数据
            {
                modelList = OperateSession.getList<Model.PerformancePrjEntry>(GlobalConstant.PARAM_DOC);
            }
            else
            {
                BLL.PerformancePrjEntry positionBll = new BLL.PerformancePrjEntry();
                modelList = positionBll.GetModelList("FPerformancePrjID=" + No);
            }


            return PartialView("PerformancePrjEntryPartial", modelList);
        }

        public ActionResult PerformancePrjEntrySave(Model.PerformancePrjEntry model)
        {
            string str = string.Empty;
            if (model.FIsPublic == "True")
            {
                model.FIsPublic = "Y";
            }
            else
            {
                model.FIsPublic = "N";
            }
            model.FInsEmpNo = OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO);
            model.FInsDate = DateTime.Now;
            model.FInsIP = Common.GenerateUtil.GetClientIPv4Address();
            model.FPerformancePrjID = decimal.Parse(Fetch.Post("hidFPerformancePrjID"));
            try
            {
                BLL.PerformancePrjEntry PerformancePrjEntryBLL = new BLL.PerformancePrjEntry();
                if (model.FPerformancePrjID == 0)//数据未保存到数据库
                {
                   
                    List<Model.PerformancePrjEntry> modelList = OperateSession.getList<Model.PerformancePrjEntry>(GlobalConstant.PARAM_DOC);
                    ///获取上传文件
                    if (Request.Files.Count > 0)
                    {
                        HttpPostedFileBase fu = Request.Files[0];
                        string type = fu.ContentType;
                        int size = fu.ContentLength;
                        if (size > 0)
                        {
                            string factFileName = Path.GetFileNameWithoutExtension(fu.FileName);

                            //获取文件的扩展名
                            string extension = Path.GetExtension(fu.FileName).ToLower();
                            string url = "/ElingOA6_Admin_DSJCJ/" + "Publish/PerformancePrj/" + DateTime.Now.Year + "/" + DateTime.Now.Month.ToString().PadLeft(2, '0');
                            if (size < 100 * 1024 * 1024)
                            {
                                //改变附件名称
                                string strnewFileNmae = GenerateUtil.GenerateStringId();
                                //判断附件保存文件夹是否存在
                                GenerateUtil.Addfolder(url);
                                string fullpath = System.Web.HttpContext.Current.Server.MapPath(url) + "\\" + strnewFileNmae + extension;

                                //判断是否存在相同的文件
                                if (System.IO.File.Exists(fullpath) == false)
                                {
                                    //上传文件到硬盘
                                    fu.SaveAs(fullpath);
                                    model.FAttachSvrFileName = url + "/" + strnewFileNmae + extension;
                                    model.FAttachOldFileName = factFileName + extension;
                                    //获取文件二进制格式
                                    System.IO.Stream stream = fu.InputStream;
                                    byte[] buffer = new byte[stream.Length];
                                    stream.Read(buffer, 0, (int)stream.Length);
                                    stream.Close();
                                    //docAttachModel.FAttachContent = buffer;
                                    model.FAttachFileExt = type;
                                }
                            }

                            if (modelList == null)
                            {
                                model.FPerformancePrjEntryID = 1;
                                modelList = new List<Model.PerformancePrjEntry>();
                            }
                            else
                            {
                                model.FPerformancePrjEntryID = modelList.Count + 1;
                            }
                            model.FEntityNo = Common.GlobalConstant.ENTITYNO;
                            modelList.Add(model);
                            OperateSession.addList(GlobalConstant.PARAM_DOC, modelList);
                            str = "ok";
                        }
                        else
                        {
                            str = "文件没有内容，无法上传";
                        }
                    }

                }
                else
                {
                    List<Model.PerformancePrjEntry> modelList = OperateSession.getList<Model.PerformancePrjEntry>(GlobalConstant.PARAM_DOC);
                    if (Request.Files.Count > 0)
                    {
                        HttpPostedFileBase fu = Request.Files[0];
                        string type = fu.ContentType;
                        int size = fu.ContentLength;
                        if (size > 0)
                        {
                            string factFileName = Path.GetFileNameWithoutExtension(fu.FileName);

                            //获取文件的扩展名
                            string extension = Path.GetExtension(fu.FileName).ToLower();
                            string url = "/ElingOA6_Admin_DSJCJ/" + "Publish/Task/" + DateTime.Now.Year + "/" + DateTime.Now.Month.ToString().PadLeft(2, '0');
                            if (size < 100 * 1024 * 1024)
                            {
                                //改变附件名称
                                string strnewFileNmae = GenerateUtil.GenerateStringId();
                                //判断附件保存文件夹是否存在
                                GenerateUtil.Addfolder(url);
                                string fullpath = System.Web.HttpContext.Current.Server.MapPath(url) + "\\" + strnewFileNmae + extension;

                                //判断是否存在相同的文件
                                if (System.IO.File.Exists(fullpath) == false)
                                {
                                    //上传文件到硬盘
                                    fu.SaveAs(fullpath);
                                    model.FAttachSvrFileName = url + "/" + strnewFileNmae + extension;
                                    model.FAttachOldFileName = factFileName + extension;
                                    //获取文件二进制格式
                                    System.IO.Stream stream = fu.InputStream;
                                    byte[] buffer = new byte[stream.Length];
                                    stream.Read(buffer, 0, (int)stream.Length);
                                    stream.Close();
                                    //docAttachModel.FAttachContent = buffer;
                                    model.FAttachFileExt = type;
                                }
                            }

                            model.FEntityNo = Common.GlobalConstant.ENTITYNO;
                            PerformancePrjEntryBLL.Add(model);
                            str = "ok";
                        
                        }
                        else
                        {
                            str = "文件没有内容，无法上传";
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                str = ex.Message.ToString();
            }

            BLL.PerformanceFileCls PerformanceFileClsBLL = new BLL.PerformanceFileCls();
            ViewData["PerformanceFileClsList"] = PerformanceFileClsBLL.GetModelList("");
            ViewData["jsAlert"] = str;
            try
            {
                if (str != "ok")
                {
                    if (Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(model.FAttachSvrFileName)))
                    {
                        Directory.Delete(System.Web.HttpContext.Current.Server.MapPath(model.FAttachSvrFileName), true);
                    }
                }
            }
            catch
            { }
            return View("PerformancePrjEntryEdit", model);
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="No">编号</param>
        /// <returns>是否删除成功</returns>
        public string DelPerformance(string No)
        {
            BLL.PerformancePrjEntry PerformancePrjEntryBLL = new BLL.PerformancePrjEntry();
            List<Model.PerformancePrjEntry> PerformancePrjEntryList = PerformancePrjEntryBLL.GetModelList("FPerformancePrjID=" + No);
            BLL.PerformancePrj PerformancePrjBLL = new BLL.PerformancePrj();
            try
            {
                PerformancePrjBLL.Delete(decimal.Parse(No));
                
                foreach (Model.PerformancePrjEntry model in PerformancePrjEntryList)
                {
                    try
                    {
                        if (Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(model.FAttachSvrFileName)))
                        {
                            Directory.Delete(System.Web.HttpContext.Current.Server.MapPath(model.FAttachSvrFileName), true);
                        }
                    }
                    catch
                    {
 
                    }
                }
            }
            catch
            {

                return "error";
            }

            return "ok";
        }

        public string PerformancePrjEntryDel(string fPerformancePrjID,string No)
        {
            string str = string.Empty;
            if (null != No)
            {
                No = Fetch.estimateString(No, CheckGetEnum.Safety);

                if (fPerformancePrjID=="0")//数据未保存到数据库
                {
                    List<Model.PerformancePrjEntry> modelList = OperateSession.getList<Model.PerformancePrjEntry>(GlobalConstant.PARAM_DOC);
                    var query = modelList.Where(c => c.FPerformancePrjEntryID == decimal.Parse(No));
                    if (query.Count() > 0)
                    {
                        try
                        {
                            if (Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(query.First().FAttachSvrFileName)))
                            {
                                Directory.Delete(System.Web.HttpContext.Current.Server.MapPath(query.First().FAttachSvrFileName), true);
                            }
                        }
                        catch
                        { }
                        modelList.Remove(query.First());
                        for (int i = 0; i < modelList.Count; i++)
                        {
                            modelList[i].FPerformancePrjEntryID = i + 1;
                        }
                        str = "ok";
                    }
                    else
                    {
                        str = "no";
                    }
                }
                else
                {
                    fPerformancePrjID = Fetch.estimateString(fPerformancePrjID, CheckGetEnum.Safety);

                    BLL.PerformancePrjEntry positionBll = new BLL.PerformancePrjEntry();
                    try
                    {
                        Model.PerformancePrjEntry PerformancePrjEntryModel = positionBll.GetModel(decimal.Parse(No));
                        positionBll.Delete(decimal.Parse(No));
                        try
                        {
                            if (Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(PerformancePrjEntryModel.FAttachSvrFileName)))
                            {
                                Directory.Delete(System.Web.HttpContext.Current.Server.MapPath(PerformancePrjEntryModel.FAttachSvrFileName), true);
                            }
                        }
                        catch
                        { }
                        str = "ok";
                    }
                    catch (Exception)
                    {
                        str = "error";
                    }
                }
            }

            return str;
        }

        public ActionResult Save(Model.PerformancePrj PerformancePrjModel)
        {
            PerformancePrjModel.FPerformancePrjID = decimal.Parse(Fetch.Post("hidFPerformancePrjID"));
            try
            {
                BLL.PerformancePrj PerformancePrjBLL = new BLL.PerformancePrj();
                if (PerformancePrjModel.FPerformancePrjID != 0)
                {
                    PerformancePrjModel.FUpdDate = DateTime.Now;
                    PerformancePrjModel.FUpdEmpNo = OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO);
                    PerformancePrjModel.FUpdIP = Common.GenerateUtil.GetClientIPv4Address();
                    PerformancePrjModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                    PerformancePrjBLL.Update(PerformancePrjModel);
                    ViewData["jsAlert"] = "ok";
                }
                else
                {
                    PerformancePrjModel.FInsDate = DateTime.Now;
                    PerformancePrjModel.FInsEmpNo = OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO);
                    PerformancePrjModel.FInsIP = Common.GenerateUtil.GetClientIPv4Address();
                    PerformancePrjModel.FEntityNo = Common.GlobalConstant.ENTITYNO;

                    List<Model.PerformancePrjEntry> PerformancePrjEntryList = OperateSession.getList<Model.PerformancePrjEntry>(GlobalConstant.PARAM_DOC);

                    PerformancePrjBLL.Add(PerformancePrjModel, PerformancePrjEntryList);
                    ViewData["jsAlert"] = "ok";
                }
            }
            catch
            {
                ViewData["jsAlert"] = "error";
            }
            OperateSession.addList(GlobalConstant.PARAM_DOC, new List<Model.PerformancePrjEntry>());
             BLL.PerformancePrjEntry PerformancePrjEntryBLL = new BLL.PerformancePrjEntry();
             ViewData["PerformancePrjEntryList"] = PerformancePrjEntryBLL.GetModelList("FPerformancePrjID=" + PerformancePrjModel.FPerformancePrjID);
             return View("PerformanceEdit", PerformancePrjModel);
        }

        public ActionResult PerformancePrjEntryEdit(string FPerformancePrjID)
        {
            BLL.PerformanceFileCls PerformanceFileClsBLL = new BLL.PerformanceFileCls();
            Model.PerformancePrjEntry positionObj = new Model.PerformancePrjEntry();
            ViewData["PerformanceFileClsList"] = PerformanceFileClsBLL.GetModelList("");
            ViewData["jsAlert"] = "";
            if (FPerformancePrjID == null)
            {
                //if (FPerformancePrjEntryID != null)
                //{
                //    List<Model.PerformancePrjEntry> modelList = OperateSession.getList<Model.PerformancePrjEntry>(GlobalConstant.PARAM_DOC);
                //    var query = from c in modelList where c.FPerformancePrjEntryID == decimal.Parse(FPerformancePrjEntryID) select c;
                //    if (query.Count() > 0)
                //    {
                //        positionObj = query.First();
                //    }
                //}
                //else
                //{
                //}

            }
            else
            {
                FPerformancePrjID = Fetch.estimateString(FPerformancePrjID, CheckGetEnum.Safety);
                //if (FPerformancePrjEntryID != null)
                //{
                //    FPerformancePrjEntryID = Fetch.estimateString(FPerformancePrjEntryID, CheckGetEnum.Safety);

                //    BLL.PerformancePrjEntry positionBll = new BLL.PerformancePrjEntry();
                //    positionObj = positionBll.GetModel(decimal.Parse(FPerformancePrjEntryID));
                //    if (null == positionObj)
                //    {
                //        positionObj = new Model.PerformancePrjEntry();
                //    }
                //}
                //else
                //{
                //    positionObj.FPerformancePrjID = decimal.Parse(FPerformancePrjID);
                //}
                positionObj.FPerformancePrjID = decimal.Parse(FPerformancePrjID);
            }
            return View(positionObj);
        }


        public ActionResult PerformancePartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();
            string type = Request.Params["Type"];
            string gNO = Request.Params["gNO"];
            string dutyNo = Request.Params["DutyNo"];

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }
            string strwhere = "";
            List<Model.PerformancePrj> PerformancePrjList = GetPerformancePrjListList(strwhere, pageIndex);
            return PartialView("PerformancePartial", PerformancePrjList);
        }

        /// <summary>
        /// 获取定义的工作时间数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        /// <param name="pageIndex">第几页</param>
        /// <returns>查询出来的数据</returns>
        private List<Model.PerformancePrj> GetPerformancePrjListList(string strWhere, int pageIndex)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.PerformancePrj TaskBLL = new BLL.PerformancePrj();
            string fiedls = "*";
            int total;
            DataSet ds = commonBll.GetListByPage("dbo.t_PerformancePrj", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "FPerformancePrjID", 0, out total);
            List<ElingOA6_Admin_DSJCJ.Model.PerformancePrj> PerformancePrjList = TaskBLL.DataTableToList(ds.Tables[0]);
            List<Model.PerformancePrj> PerformancePrjAllList = new List<Model.PerformancePrj>();

            int pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                PerformancePrjAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (PerformancePrjList.Count > i)
                {
                    PerformancePrjAllList[((pageIndex - 1) * pageRowSize) + i] = PerformancePrjList[i];
                }
            }

            return PerformancePrjAllList;
        }

    }
}
